<template>
  <a-modal
    v-model:visible="dialogVisible"
    width="80%"
    title="岗位选择弹窗"
    ok-text="提交"
    @ok="handleOk"
  >
    <div class="authManage-container">
      <a-row :gutter="10">
        <!-- 树搜索 -->
        <a-col
          :span="7"
          style="padding-left: 20px"
        >
          <!-- 公司组织树搜索 -->
          <tree-organization
            ref="treeOrganization"
            :expand-by-auto="true"
            :selected-keys.sync="selectedKeys"
            :select-options.sync="selectOptions"
            :expanded-keys="expandedKeys"
            :show-child-with-search="true"
            :filter-fn="handleFilterTree"
            :auto-select="false"
            :contain-virtual="false"
            :org-query="{
              baseOrgType: 1, // 是否基础组织 0否 1是
              systemOrgType: 1 //公司组织默认1
            }"
            @onSelect="handleSelect"
            @searchEmpty="handleSearchEmpty"
            @initFinish="initFinish"
          />
        </a-col>
        <a-col :span="17">
          <div
            class="search"
            style="margin-bottom: 10px"
          >
            <a-row :gutter="[10]">
              <a-col :span="10">
                <div style="display: flex;align-items: center; height: 32px">
                  <div style="width: 100px;text-align: right">
                    岗位名称：
                  </div>
                  <a-input
                    v-model="postName"
                    allowClear
                    placeholder="请输入岗位名称"
                  />
                </div>
              </a-col>
              <a-col :span="8" />
              <a-col :span="6">
                <a-button
                  type="primary"
                  style="margin-right: 10px"
                  @click="search"
                >
                  搜索
                </a-button>
                <a-button @click="reset">
                  重置
                </a-button>
              </a-col>
            </a-row>
          </div>
          <div
            class="scorll-area"
            style="margin-bottom: 15px"
          >
            <div
              v-for="(item, index) in postList"
              :key="item.id"
              class="cell"
            >
              {{ item.pname }}
              <div
                class="del"
                @click="delCell(item, index)"
              >
                x
              </div>
            </div>
          </div>
          <list-table
            ref="table"
            :columns="columns"
            :request="loadData"
            :alert="true"
            row-key="id"
            :row-selection="rowSelection"
            :is-init="false"
          >
            <template
              slot="sort"
              slot-scope="text, record, index"
            >
              <span>{{ index + 1 }}</span>
            </template>
          </list-table>
        </a-col>
      </a-row>
    </div>
  </a-modal>
</template>
<script>
import { pageByBasePost, updatePost } from '@/api/system/system'
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    width: '65px',
    scopedSlots: { customRender: 'sort' }
  },
  {
    title: '岗位名称',
    dataIndex: 'name'
  },
  {
    title: '岗位层级',
    dataIndex: 'pname'
  }
]
export default {
  components: {
    TreeOrganization
  },
  props: {
    selectPost: {
      type: Array,
      default: () => []
    },
    id: {
      type: String,
      defalut: ''
    }
  },
  data() {
    this.columns = columns
    return {
      dialogVisible: false,
      postName: '',
      isExtend: '',
      childInitData: {},
      visible: {
        update: false,
        auth: false
      },
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      expandedKeys: [],
      queryParam: {},
      statisticsInfo: {
        totalNum: 0
      },
      selectedRowKeys: [],
      selectedRows: [],
      tableData: [],
      postList: [],
      cacheTableData: [],
      cacheSelectedRowKeys: [],
      isFirst: true
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  watch: {
    dialogVisible(newVal, oldVal) {
      if (newVal) {
        this.$nextTick(() => {
          // 组织树获取数据
          if (this.isFirst) {
            this.isFirst = false
            this.$refs.treeOrganization.getList()
          }
        })
        if (this.selectPost.length) {
          this.postList = this.selectPost
          const ids = []
          this.selectPost.forEach((item) => {
            ids.push(item.id)
          })
          this.cacheSelectedRowKeys = ids
          const newId = []
          if (this.tableData.length) {
            this.tableData.forEach((item) => {
              if (this.cacheSelectedRowKeys.includes(item.id)) {
                newId.push(item.id)
              }
            })
          }
          this.selectedRowKeys = newId
        } else {
          this.cacheSelectedRowKeys = []
          this.selectedRowKeys = []
        }
      } else {
        this.cacheSelectedRowKeys = []
        this.selectedRowKeys = []
        this.postList = []
      }
    }
  },
  methods: {
    initFinish(data) {
      console.log(data, 'data')
      this.queryParam.orgId = data.data[0].id
      this.queryParam.orgCode = data.data[0].data.code
      this.expandedKeys = [data.data[0].id]
      this.$refs.table.getData()
    },
    delCell(row, i) {
      const idx = this.selectedRowKeys.findIndex((item) => item === row.id)
      if (idx >= 0) {
        this.selectedRowKeys.splice(idx, 1)
      }
      this.postList.splice(i, 1)
    },
    handleOk() {
      if (this.id) {
        const arr = []
        this.postList.forEach((item) => {
          const obj = {
            postCode: item.code,
            postId: item.id,
            postName: item.pname
          }
          arr.push(obj)
        })
        const data = {
          id: this.id,
          postList: arr
        }
        updatePost(data).then((res) => {
          this.$message.success('绑定成功')
          this.$emit('updateList')
          this.close()
        })
      } else {
        this.$emit('setPost', this.postList)
      }
    },
    handleFilterTree(data) {
      return data.label !== '分包商'
    },
    open() {
      this.dialogVisible = true
    },
    close() {
      this.dialogVisible = false
    },
    findId(arr, id) {
      let flag = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === id) {
          flag = true
          break
        }
      }
      return flag
    },
    onSelectChange(selectedRowKeys, row) {
      this.selectedRowKeys = selectedRowKeys
      const cancelId = []
      this.tableData.forEach((item) => {
        if (!selectedRowKeys.includes(item.id)) {
          cancelId.push(item.id)
        }
      })
      this.cacheSelectedRowKeys.push(...selectedRowKeys)
      const arr = []
      //去重
      this.cacheSelectedRowKeys.forEach((item) => {
        if (!arr.includes(item)) {
          arr.push(item)
        }
      })
      const newId = []
      arr.forEach((item) => {
        if (!cancelId.includes(item)) {
          newId.push(item)
        }
      })

      this.cacheSelectedRowKeys = newId
      console.log(this.cacheSelectedRowKeys, 'ca')

      //找岗位
      const newPost = []
      this.postList.forEach((item) => {
        if (this.cacheSelectedRowKeys.includes(item.id)) newPost.push(item)
      })
      //
      const newTPost = []
      this.tableData.forEach((item) => {
        if (this.cacheSelectedRowKeys.includes(item.id)) {
          newTPost.push(item)
        }
      })

      this.postList = [...newPost, ...newTPost]
      //去重
      const arrLast = []
      this.postList.forEach((item) => {
        if (!this.findId(arrLast, item.id)) {
          arrLast.push(item)
        }
      })
      console.log(arrLast, 'arrLast')
      this.postList = arrLast
    },
    handleSearchEmpty() {
      this.selectedKeys = []
      this.selectOptions = {}
    },
    handleSelect(e) {
      this.handleSearch({
        orgId: e.id || void 0,
        orgCode: e.code
      })
    },
    async loadData(parameter) {
      //parameter
      const requestParameters = Object.assign({}, this.queryParam, {
        pageIndex: parameter.pageNo,
        pageSize: parameter.pageSize
      })
      return pageByBasePost(requestParameters).then((res) => {
        res.data.list.forEach((item) => {
          if (!item.pname) {
            item.pname = item.orgName || item.name
          }
        })
        const obj = {
          code: '0',
          data: res.data.list,
          totalSize: res.data.total
        }
        this.tableData = res.data.list
        const data = []
        this.tableData.forEach((item) => {
          if (this.cacheSelectedRowKeys.includes(item.id)) {
            data.push(item.id)
          }
        })
        // 当前页
        this.selectedRowKeys = data
        return obj
      })
    },
    search() {
      this.queryParam.postName = this.postName
      this.$refs.table.refresh(true)
    },
    reset() {
      this.postName = ''
      this.queryParam.postName = ''
      this.$refs.table.refresh(true)
    },
    handleSearch(val) {
      this.queryParam = {
        ...this.queryParam,
        ...val
      }
      this.$refs.table.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
.ellipsis {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  white-space: nowrap;
}

.cell {
  padding-left: 10px;
  padding-right: 20px;
  position: relative;
  background: #108eea;
  color: #fff;
  min-width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.scorll-area {
  height: 100px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  scrollbar-width: thin;
  scrollbar-color: #ccc transparent;
  scrollbar-track-color: #fff;
  -ms-scrollbar-track-color: transparent;

  &::-webkit-scrollbar {
    background: #fff;
    width: 8px;
    height: 8px;
    // display: none;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    width: 8px;
    border-radius: 8px;
    border: 1px #fff solid;
    background: #ccc;
  }
}

.del {
  position: absolute;
  right: 5px;
  top: 0;
  cursor: pointer;
}

/deep/ .anticon-setting.tableIcon {
  display: none;
}

/deep/ .treeBox {
  max-height: calc(var(--heightVh) * 0.58);
  overflow-y: auto;
}

/deep/ .list-table {
  max-height: calc(var(--heightVh) * 0.52);
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #ccc transparent;
  scrollbar-track-color: #fff;
  -ms-scrollbar-track-color: transparent;

  &::-webkit-scrollbar {
    background: #fff;
    width: 8px;
    height: 8px;
    // display: none;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    width: 8px;
    border-radius: 8px;
    border: 1px #fff solid;
    background: #ccc;
  }
}
</style>
